/*
 * Copyright:  2018 smarabbit studio.
 *
 *  Licensed under the Confluent Community License; you may not use this file
 *  except in compliance with the License.  You may obtain a copy of the License at
 *
 *  http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OF ANY KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期:  2020年9月12日
 */
package com.massyframework.beanskin.runtime.framework.installing.strategy;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.function.Consumer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.massyframework.beanskin.Module;
import com.massyframework.beanskin.assembly.AssemblyContext;
import com.massyframework.beanskin.assembly.AssemblyContextSupport;

import com.massyframework.beanskin.service.ServiceEvent;
import com.massyframework.beanskin.service.ServiceListener;
import com.massyframework.beanskin.service.ServiceRegistedEvent;
import com.massyframework.beanskin.service.ServiceRepository;
import com.massyframework.beanskin.service.ServiceUnregistingEvent;
import com.massyframework.beanskin.service.awaitstrategy.AwaitStrategy;
import com.massyframework.beanskin.service.awaitstrategy.AwaitStrategyBuilder;
import com.massyframework.beanskin.service.awaitstrategy.AwaitStrategyRepository;

/**
 * 缺省的等待策略仓储
 * @author huangkh
 *
 */
public final class DefaultAwaitStrategyRepository extends AssemblyContextSupport 
	implements AwaitStrategyRepository {
	
	private Logger logger = LoggerFactory.getLogger(DefaultAwaitStrategyRepository.class);
	
	private Set<DefaultAwaitStrategy> strategies;
	private ServiceListener listener;

	/**
	 * 构造方法
	 */
	public DefaultAwaitStrategyRepository() {
		this.strategies = new CopyOnWriteArraySet<>();
	}
	
	@Override
	protected synchronized void bindAssemblyContext(AssemblyContext context) {
		if (this.listener == null) {
			this.listener = new ServiceListenerImpl();
			
			ServiceRepository repo = 
					ServiceRepository.retrieveFrom(context.getAssociatedAssembly());
			repo.addListener(this.listener);
		}
		super.bindAssemblyContext(context);
	}

	@Override
	protected synchronized void unbindAssemblyContext(AssemblyContext context) {
		if (this.listener != null) {
			ServiceRepository repo = 
					ServiceRepository.retrieveFrom(context.getAssociatedAssembly());
			repo.removeListener(this.listener);
			this.listener = null;
		}	
		super.unbindAssemblyContext(context);
	}
	
	/**
	 * 等待策略数量
	 * @return {@link int}
	 */
	public int size() {
		return this.strategies.size();
	}

	@Override
	public void addStrategy(Module<?> module, Consumer<AwaitStrategyBuilder> consumer) {
		if (consumer != null) {
			DefaultAwaitStrategy.Builder builder = DefaultAwaitStrategy.newBuilder(module);
			consumer.accept(builder);
			
			DefaultAwaitStrategy strategy = builder.build();
			this.strategies.add(strategy);
			if (strategy.isAllMatch()) {
				this.strategies.remove(strategy);
				try {
					strategy.doAction();
				}catch(Exception e) {
					if (logger.isErrorEnabled()) {
						logger.error(e.getMessage(), e);
					}
				}
			}
		}
	}
	
	@Override
	public Map<Module<?>, List<AwaitStrategy>> getAwaitStrategies() {
		Map<Module<?>, List<AwaitStrategy>> result = new HashMap<>();
		for (DefaultAwaitStrategy awaitStrategy: strategies) {
			List<AwaitStrategy> list = result.computeIfAbsent(
					awaitStrategy.getModule(), key -> new ArrayList<AwaitStrategy>());
			list.add(awaitStrategy);
		}
		return result;
	}

	private class ServiceListenerImpl implements ServiceListener {

		@Override
		public void onChanged(ServiceEvent<?> event) {
			if (event instanceof ServiceRegistedEvent) {
				this.onRegisted((ServiceRegistedEvent<?>)event); 
				return;
			}
			
			if (event instanceof ServiceUnregistingEvent) {
				this.onUnregisting((ServiceUnregistingEvent<?>)event);
				return;
			}
		}
		
		protected void onRegisted(ServiceRegistedEvent<?> event) {
			List<DefaultAwaitStrategy> matched = new ArrayList<>();
			for (DefaultAwaitStrategy strategy:  strategies) {
				if (strategy.matchedAll(event)) {
					matched.add(strategy);
				}
			}
			
			for (DefaultAwaitStrategy strategy: matched) {
				strategies.remove(strategy);
				try {
					strategy.doAction();
				}catch(Exception e) {
					if (logger.isErrorEnabled()) {
						logger.error(e.getMessage(), e);
					}
				}
			}
		}
		
		protected void onUnregisting(ServiceUnregistingEvent<?> event) {
			for (DefaultAwaitStrategy strategy:  strategies) {
				 strategy.onServiceUnregisting(event);
			}
		}
		
	}
}
